﻿using CRM.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace CRM.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class BaseController : ControllerBase
    {
        protected bool HasPermission<TEnum>(TEnum @enum)
        {
            return User.HasPermission(@enum);
        }

        protected IActionResult Json(object data = null)
        {

            return new JsonResult(data);
            //var res = JsonConvert.SerializeObject(data);
            //Response.StatusCode = 200;
            //Response.ContentType = "application/json;charset=UTF-8";
            //return Response.WriteAsync(res);
        }
        protected ResultStruct Success(object data = null, string message = "成功")
        {
            return FormatResult(data, message, 20000);
        }

        protected ResultStruct Error(object data = null, string message = "失败", string tag = null)
        {
            return FormatResult(data, message, 100, tag);
        }

        private ResultStruct FormatResult(object data, string message, int code, string tag = null)
        {

            return new() { Data = data, Message = message, Code = code, Tag = tag };
        }
        
        protected ResultStruct<T> SuccessGeneric<T>(T data, string message = "成功")
        {
            return FormatResult(data, message, 20000);
        }
        private ResultStruct<T> FormatResult<T>(T data, string message, int code, string tag = null)
        {

            return new() { Data = data, Message = message, Code = code, Tag = tag };
        }
        public struct ResultStruct
        {
            [JsonProperty("message")]
            public string Message { get; set; }
            [JsonProperty("data")]
            public object Data { get; set; }
            [JsonProperty("code")]
            public int Code { get; set; }
            [JsonIgnore]
            public object Tag;
        }
        
        public struct ResultStruct<TData>
        {
            [JsonProperty("message")]
            public string Message { get; set; }
            [JsonProperty("data")]
            public TData Data { get; set; }
            [JsonProperty("code")]
            public int Code { get; set; }
            [JsonIgnore]
            public object Tag;
        }
    }
}
